<script setup lang="ts">
import { getTaskTagApi, addTagApi, TagOption } from '@/common/apis/tag';
import { cloneDeep, isEmpty } from 'lodash-es';

interface Props {
  module: string // entity实体  gjb军标  3dmodel三维模型  train训练  deduct 推演 component组件模型 basicData基础数据
  task_tags?: string[]
  maxCollapseTags?: number
}

const props = defineProps<Props>()
const emit = defineEmits(["update:task_tags", "update:uploadType"])
const options = ref<TagOption[]>([])
const task_tag = ref<string[]>(props.task_tags || [])
const loading = ref(false)

const createOptionValidator = (value: string) => {
  // 验证标签名称
  if (!value.trim()) {
    ElMessage.warning('标签名称不能为空')
    return false
  }
  // 检查是否已存在
  const exists = options.value.some(option => {
    return !isEmpty(option.name) && option.name.toLowerCase() === value.toLowerCase()
  })
  if (exists) {
    ElMessage.warning('标签已存在')
    return false
  }

  return true
}

const handleChange = async (value: string[]) => {
  const lastTag = value[value.length - 1]
  const isNewTag = !options.value.some(option => option.name === lastTag)

  if (isNewTag && lastTag) {
    // 验证新标签
    if (!createOptionValidator(lastTag)) {
      // 如果验证失败，从选中值中移除新标签
      task_tag.value = task_tag.value.filter(tag => tag !== lastTag)
      return
    }

    try {
      loading.value = true
      // await addTagApi({ name: lastTag, module: props.module })
      // await getTagOptions()
    } catch (error) {
      // 如果添加失败，从选中值中移除新标签
      task_tag.value = task_tag.value.filter(tag => tag !== lastTag)
      return
    } finally {
      loading.value = false
    }
  }

  emit("update:task_tags", task_tag.value)
}
const getTagOptions = async () => {
  try {
    loading.value = true
    const { data } = await getTaskTagApi({ module: props.module })
    options.value = data.filter(tag => !isEmpty(tag.name))
  } catch (error) {
    console.error('获取标签失败:', error)
    ElMessage.error('获取标签列表失败')
  } finally {
    loading.value = false
  }
}
watch(
  () => props.task_tags,
  (newValue) => {
    if (newValue) {
      task_tag.value = cloneDeep(newValue)
    }
  },
  { immediate: true }
)

onMounted(() => {
  getTagOptions()
})
</script>
<template>
  <el-select
    v-model="task_tag"
    multiple
    filterable
    allow-create
    default-first-option
    :multiple-limit="5"
    :loading="loading"
    :reserve-keyword="false"
    :max-collapse-tags="maxCollapseTags != undefined ? maxCollapseTags : 5"
    collapse-tags
    collapse-tags-tooltip
    placeholder="请选择或输入"
    @change="handleChange"
  >
    <el-option
      v-for="item in options"
      :key="item.name"
      :label="item.name"
      :value="item.name"
    />
  </el-select>
</template>